import styles from '../../index.less';
import styles2 from './index.less';
import React, { useState, useEffect, useRef, memo } from 'react';
import kls from 'classnames';
import { Tabs, Select } from 'antd';
import { CloseOutlined, PhoneOutlined, EnvironmentOutlined } from '@ant-design/icons';
import layerUtils from '@/utils/arcgis/layer/index';
import { jsapi, viewUtils } from '@/utils/arcgis';
import TransporterChart from './transporter-chart';

const { Option } = Select;
const VEHICLE_TAG = 'vehicleLayer';

const lineSymbol = {
  type: 'simple-line', // autocasts as SimpleLineSymbol()
  color: [52, 179, 187],
  width: 4,
};
var fwySym = {
  type: 'simple-line', // autocasts as new SimpleLineSymbol()
  color: '#FFAA00',
  width: 4,
  style: 'solid',
};

var hwySym = {
  type: 'simple-line', // autocasts as new SimpleLineSymbol()
  color: '#DF73FF',
  width: 4,
  style: 'solid',
};

async function hideLayer() {
  const view = await viewUtils.isViewReady();
  let routeLayer = layerUtils.getLayerByTitle(view, VEHICLE_TAG);
  if (routeLayer) {
    routeLayer.visible = false;
  }
}

function Transporter({ vehicleData }) {
  const [curTracker, setCurTracker] = useState(null);
  const legendRef = useRef(null);
  // const legendObjRef = useRef(null)
  let chartData =
    curTracker && vehicleData && vehicleData[curTracker] ? vehicleData[curTracker].rawData : null;
  useEffect(() => {
    if (!vehicleData) {
      return;
    }
    setCurTracker(Object.keys(vehicleData)[0]);
    createDangerPathLayer(vehicleData);
  }, [vehicleData]);

  useEffect(() => {
    return () => {
      try {
        hideLayer();
      } catch (error) {}
    };
  }, []);

  async function showLayer() {
    const view = await viewUtils.isViewReady();
    let lyr = layerUtils.getLayerByTitle(view, VEHICLE_TAG);
    if (lyr) {
      lyr.visible = true;
      return lyr;
    }
    return null;
  }

  async function createDangerPathLayer(allVehicleData) {
    const [Graphic, FeatureLayer, Legend] = await jsapi.load([
      'esri/Graphic',
      'esri/layers/FeatureLayer',
      'esri/widgets/Legend',
    ]);
    const view = await viewUtils.isViewReady();
    let routeLayer = await showLayer();
    if (!routeLayer) {
      const graphics = Object.keys(allVehicleData).map(_key => {
        const item = allVehicleData[_key];
        const { paths, rawData } = item;

        let cfg = {
          geometry: {
            type: 'polyline', // autocasts as new Polyline()
            paths: paths,
          },
          symbol: lineSymbol,
          attributes: {
            ...rawData[0],
            rawData,
          },
        };
        return new Graphic(cfg);
      });
      routeLayer = new FeatureLayer({
        title: VEHICLE_TAG,
        id: VEHICLE_TAG,
        source: graphics, // array of graphics objects
        objectIdField: 'OBJECTID',
        fields: [
          {
            name: 'OBJECTID',
            type: 'oid',
          },
          {
            name: 'xt',
            type: 'string',
          },
          {
            name: 'updateTime',
            type: 'string',
          },
        ],
        // popupTemplate: {
        //   // content: "<img src='{url}'>",
        // },
        renderer: {
          type: 'unique-value', // autocasts as new UniqueValueRenderer()
          defaultSymbol: lineSymbol,
          defaultLabel: '其他主要线路',
          field: 'xt',
          uniqueValueInfos: [
            {
              value: '2', // code for interstates/freeways
              symbol: fwySym,
              label: '2',
            },
            {
              value: '3', // code for U.S. highways
              symbol: hwySym,
              label: '3',
            },
          ],
        },
      });

      new Legend({
        view: view,
        container: legendRef.current,
        layerInfos: [
          {
            layer: routeLayer,
            title: '运输车轨迹',
          },
        ],
      });
      view.map.add(routeLayer);
      view.goTo(graphics[0].geometry);
    }

    // routeLayer.graphics = graphics;
    // return routeLayer;
    // view.goTo(graphics[0]);
  }

  return (
    <div className={styles.transporter}>
      <Select
        value={curTracker}
        size={'small'}
        style={{ marginRight: 10 }}
        onChange={e => setCurTracker(e)}
      >
        {!!vehicleData &&
          Object.keys(vehicleData).map(_key => {
            return (
              <Option key={_key} value={_key}>
                {_key}
              </Option>
            );
          })}
      </Select>
      <p style={{ position: 'absolute', right: 16, top: 68, opacity: 0.8 }}>单位：km/h</p>
      <TransporterChart data={chartData} />
      <div
        ref={legendRef}
        className={kls('base-panel-body', styles2.legend)}
        style={{
          position: 'fixed',
          bottom: 360,
          right: 476,
          color: '#fff',
        }}
      ></div>
    </div>
  );
}

export default Transporter;
